package com.kacheong.pms.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kacheong.pms.POJO.PageBean;
import com.kacheong.pms.Value.StaticValue;
import com.kacheong.pms.dao.*;
import com.kacheong.pms.domain.*;
import com.kacheong.pms.service.IGarageConfigService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/config")
public class GarageConfigController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IDeviceDao deviceDao;

    @Autowired
    private IDeviceTypeDao deviceTypeDao;

    @Autowired
    private ILocationDao locationDao;

    @Autowired
    private IGarageConfigService garageConfigService;

    @Autowired
    private IGarageDao garageDao;

    @Autowired
    private IAreaDao areaDao;

    @Autowired
    private IPositionDao positionDao;

    @Autowired
    private IPublicityDao publicityDao;

    @Autowired
    private  IExpendTypeDao expendTypeDao;

    @Autowired
    private IExpendDao expendDao;

    @RequestMapping("/clearGarage")
    public JSONObject clearGarage(@RequestParam Integer garageId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", StaticValue.error);
        if (garageId!=null)
            if (garageDao.get(garageId)!=null){
            garageConfigService.clearGarage(garageId);
            jsonObject.put("msg",StaticValue.success);
        }
        return jsonObject;
    }

    @RequestMapping("/initDefaultGarage")
    public JSONObject initDefaultGarage(@RequestParam Integer garageId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", StaticValue.error);
        if (garageId!=null)
            if (garageDao.get(garageId)!=null){
                garageConfigService.initDefaultGarage(garageId);
                jsonObject.put("msg",StaticValue.success);
            }
        return jsonObject;
    }

    @RequestMapping("/initPosition")
    public JSONObject initPosition(@RequestParam Integer areaId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",StaticValue.error);
        if (areaId!=null) {
            if (areaDao.get(areaId)!=null){
                garageConfigService.initPosition(areaId);
                jsonObject.put("msg",StaticValue.success);
                return jsonObject;
            }
        }
        return jsonObject;
    }

    @RequestMapping(value = "/getPositions",method = RequestMethod.POST)
    public JSONArray getPositions(@RequestBody Map<String,Object> params){
        JSONArray jsonArray = new JSONArray();
        String hql = "FROM Position position WHERE position.area.id = ?";
        String page= (String) params.get("page");
        Integer currentPage = (Integer) params.get("currentPage");
        Integer id = (Integer) params.get("areaId");
        List list = new ArrayList();
        int total = 0;
        if (page.equals("1")){
            PageBean pageBean = positionDao.doPage(hql,currentPage,10,id);
            list = pageBean.getList();
            total = (int) pageBean.getAllRow();
        }
        if (page.equals("2")){
            hql+="AND position.status = ?";
            PageBean pageBean = positionDao.doPage(hql,1,100,id,"Empty");
            list = pageBean.getList();
        }
        for (Object aList : list) {
            JSONObject jsonObject = new JSONObject();
            Position position = (Position) aList;
            jsonObject.put("id", position.getId());
            jsonObject.put("name", position.getName());
            jsonObject.put("status", position.getStatus());
            jsonObject.put("total",total);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    @RequestMapping("/getGarageInfo")
    public JSONObject getGarageInfo(){
        JSONObject jsonObject = new JSONObject();
        Garage garage = garageDao.get(1);
        jsonObject.put("name",garage.getName());
        jsonObject.put("info",garage.getInfo());
        return jsonObject;
    }

    @RequestMapping(value = "/setGarageInfo",method = RequestMethod.POST)
    public JSONObject setGarageInfo(@RequestBody Map<String,Object> params){
        String info = params.get("info").toString();
        JSONObject jsonObject = new JSONObject();
        Garage garage = garageDao.get(1);
        garage.setInfo(info);
        garageDao.update(garage);
        jsonObject.put("success",garage.getInfo());
        return jsonObject;
    }

    @RequestMapping("/getPublicity")
    public JSONObject getPublicity(){
        JSONObject jsonObject = new JSONObject();
        Publicity publicity = publicityDao.get(1);
        jsonObject.put("mess",publicity.getInfo());
        return jsonObject;
    }

    @RequestMapping(value = "/getAreaList",method = RequestMethod.POST)
    public JSONArray getAreaList(@RequestBody Map<String,Object> params){
        Integer garageId = Integer.parseInt((String) params.get("garageId"));
        if (garageId!=0){
            JSONArray jsonArray = new JSONArray();
            List list = areaDao.getByGarage(garageId);
            for (Object aList : list) {
                Area area = (Area) aList;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", area.getId());
                jsonObject.put("name", area.getInfo());
                jsonArray.add(jsonObject);
            }
            return jsonArray;
        }
        return null;
    }

    @RequestMapping(value = "/addPosition",method = RequestMethod.POST)
    public JSONObject addPosition(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        Integer areaId = Integer.parseInt((String) params.get("areaId"));
        if (areaId!=0){
            int i =positionDao.getByArea(areaId).size();
            Position position = new Position();
            position.setName((i+1)+"号位");
            position.setStatus("Empty");
            position.setArea(areaDao.get(areaId));
            positionDao.save(position);
            jsonObject.put("msg",StaticValue.success);
            return jsonObject;
        }
        return null;
    }

    @RequestMapping(value = "/searchPositions",method = RequestMethod.POST)
    public JSONArray searchPositions(@RequestBody Map<String,Object> params){
        JSONArray jsonArray = new JSONArray();
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        Integer areaId = (Integer) params.get("areaId");
        if (content!=null){
            String hql = "FROM Position position WHERE CONCAT(name,status) LIKE '%"+content+"%' AND position.area.id =?" ;
            PageBean pageBean = positionDao.doPage(hql,currentPage,10,areaId);
            List list = pageBean.getList();
            for(Object aList :list){
                Position position = (Position) aList;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name",position.getName());
                jsonObject.put("status",position.getStatus());
                jsonObject.put("total",pageBean.getAllRow());
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }

    @RequestMapping("/addLocation")
    public JSONObject addLocation(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String info = (String) params.get("info");
        if (!info.equals("")){
            Location location = new Location();
            location.setName(info);
            locationDao.save(location);
            jsonObject.put("msg",StaticValue.success);
        }
        return jsonObject;
    }

    @RequestMapping("/getLocations")
    public JSONArray getLocations(@RequestBody Map<String,Object> params){
        String hql = "FROM Location";
        String status = (String) params.get("status");
        if (status!=null&&status.equals("empty")){
            hql+=" location WHERE location.advertisement.id = null";
        }
        String page= (String) params.get("page");
        Integer currentPage = (Integer) params.get("currentPage");
        PageBean pageBean = new PageBean();
        if (page.equals("1")){
            pageBean = locationDao.doPage(hql,currentPage,10);
        }
        if (page.equals("2")){
            pageBean = locationDao.doPage(hql,1,100);
        }
        return getLocations(pageBean);
    }

    @RequestMapping("/getImg")
    public JSONObject getImg(@RequestBody Map<String,Object> params){
        JSONObject jsonObject =new JSONObject();
        String url = (String) params.get("name");
        if (url!=null&&!url.equals("")){
            Location location = locationDao.getByName(url);
            if (location.getAdvertisement()!=null)
                jsonObject.put("url","http://127.0.0.1:8080/advertisement/"+location.getAdvertisement().getAdURL());
            return jsonObject;
        }
        return null;
    }

    @RequestMapping("/searchLocation")
    public JSONArray searchLocation(@RequestBody Map<String,Object> params){
        JSONArray jsonArray = new JSONArray();
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM Location location WHERE location.name like '%"+content+"%'";
            if (content.contains("空")){
                hql="FROM Location location WHERE location.advertisement.id = null";
            }
            if (content.contains("有")){
                hql="FROM Location location WHERE location.advertisement.id !=null";
            }
            PageBean pageBean = locationDao.doPage(hql,currentPage,10);
            jsonArray = getLocations(pageBean);
        }
        return jsonArray;
    }

    @RequestMapping("/delLocation")
    public JSONObject delLocation(@RequestBody Map<String,Object> params){
        String name= (String) params.get("info");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",null);
        if (name!=null&&!name.equals("")){
            String result = garageConfigService.delLocation(name);
            jsonObject.put("msg",result);
        }
        return jsonObject;
    }

    @RequestMapping("/getDeviceTypeList")
    public JSONArray getDeviceTypeList(@RequestBody Map<String,Object> params){
        JSONArray jsonArray = new JSONArray();
        String page = (String) params.get("page");
        Integer currentPage = (Integer) params.get("currentPage");
        PageBean pageBean = null;
        String hql = "FROM DeviceType";
        if (page.equals("1")){
            pageBean = deviceTypeDao.doPage(hql,currentPage,10);

        }
        else if (page.equals("2")){
            pageBean = deviceTypeDao.doPage(hql,1,100);
        }
        return getDeviceTypeList(pageBean);
    }

    @RequestMapping("/searchDeviceTypes")
    public JSONArray searchDeviceTypes(@RequestBody Map<String,Object> params){
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM DeviceType d WHERE d.type LIKE '%"+content+"%'" ;
            PageBean pageBean = deviceTypeDao.doPage(hql,currentPage,10);
            return getDeviceTypeList(pageBean);
        }
        return null;
    }

    @RequestMapping("/addDeviceType")
    public JSONObject addDeviceType(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String name = (String) params.get("name");
        if (name!=null&&!name.equals("")){
            try{
                if (deviceTypeDao.getByName(name)==null){
                    DeviceType deviceType = new DeviceType();
                    deviceType.setType(name);
                    deviceTypeDao.save(deviceType);
                    jsonObject.put("msg",StaticValue.success);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    @RequestMapping("/delDeviceType")
    public JSONObject delDeviceType(@RequestBody Map<String,Object> params){
        String type= (String) params.get("info");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",null);
        String result = garageConfigService.delDeviceType(type);
        jsonObject.put("msg",result);
        return jsonObject;
    }

    @RequestMapping("/editDeviceType")
    public JSONObject editDeviceType(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        Integer id = (Integer) params.get("id");
        String type = (String) params.get("name");
        String result = garageConfigService.editDeviceType(id,type);
        jsonObject.put("msg",result);
        return jsonObject;
    }

    @RequestMapping("/editDevice")
    public JSONObject editDevice(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        Integer id = (Integer) params.get("id");
        String type = (String) params.get("type");
        String name = (String) params.get("name");
        String location = (String) params.get("location");
        String status = (String) params.get("status");
        String result = garageConfigService.editDevice(id,type,name,location,status);
        jsonObject.put("msg",result);
        return jsonObject;
    }
    @RequestMapping("addDevice")
    public JSONObject addDevice(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String type = (String) params.get("type");
        String name = (String) params.get("name");
        String location = (String) params.get("location");
        if (type!=null&&name!=null){
            try{
                deviceTypeDao.getByName(type);
                if (deviceDao.getByName(name)==null){
                    Device device = new Device();
                    device.setDeviceType(deviceTypeDao.getByName(type));
                    device.setInfo(name);
                    device.setLocation(location);
                    device.setStatus("完好");
                    deviceDao.save(device);
                    jsonObject.put("msg",StaticValue.success);
                }
                else
                    return jsonObject;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    @RequestMapping("/getDeviceList")
    public JSONArray getDeviceList(@RequestBody Map<String,Object> params){
        String page = (String) params.get("page");
        Integer currentPage = (int) params.get("currentPage");
        PageBean pageBean = null;
        String hql = "FROM Device";
        if (page.equals("1")){
            pageBean = deviceDao.doPage(hql,currentPage,10);
        }
        else if(page.equals("2")){
            pageBean = deviceDao.doPage(hql,currentPage,100);
        }
        return getDevice(pageBean);
    }

    @RequestMapping("/searchDevice")
    public JSONArray searchDevice(@RequestBody Map<String,Object> params){
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM Device d WHERE CONCAT(d.info,d.location,d.status,d.deviceType.type) LIKE '%"+content+"%'" ;
            PageBean pageBean = deviceDao.doPage(hql,currentPage,10);
            return getDevice(pageBean);
        }
        return null;
    }

    @RequestMapping("getExpendTypeList")
    public JSONArray getExpendTypeList(@RequestBody Map<String,Object> params){
        String page = (String) params.get("page");
        Integer currentPage = (int) params.get("currentPage");
        PageBean pageBean = null;
        if (page!=null&&!page.equals("")){
            String hql = "FROM ExpendType";
            if (page.equals("1")){
                pageBean = expendTypeDao.doPage(hql,currentPage,10);
            }
            else if (page.equals("2")){
                pageBean = expendTypeDao.doPage(hql,1,101);
            }
            return getExpendTypeList(pageBean);
        }
        return null;
    }

    @RequestMapping("/searchExpendType")
    public JSONArray searchExpendType(@RequestBody Map<String,Object> params){
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM ExpendType e WHERE e.type LIKE '%"+content+"%'" ;
            PageBean pageBean = expendTypeDao.doPage(hql,currentPage,10);
            return getExpendTypeList(pageBean);
        }
        return null;
    }

    @RequestMapping(value = "addExpendType")
    public JSONObject addExpendType(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String type = (String) params.get("type");
        if (type!=null&&!type.equals("")){
            try {
                if (expendTypeDao.getByName(type)!=null){
                    jsonObject.put("msg",StaticValue.error);
                    return jsonObject;
                }
                ExpendType expendType = new ExpendType();
                expendType.setType(type);
                expendTypeDao.save(expendType);
                jsonObject.put("msg",StaticValue.success);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    @RequestMapping("/delExpendType")
    public JSONObject delExpendType(@RequestBody Map<String,Object> params){
        String type= (String) params.get("info");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",null);
        String result = garageConfigService.delExpendType(type);
        jsonObject.put("msg",result);
        return jsonObject;
    }

    @RequestMapping("/editExpendType")
    public JSONObject editExpendType(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        Integer id = (Integer) params.get("id");
        String type = (String) params.get("name");
        String result = garageConfigService.editExpendType(id,type);
        jsonObject.put("msg",result);
        return jsonObject;
    }


    @RequestMapping("/addExpend")
    public JSONObject addExpend(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        Double cost = Double.parseDouble((String) params.get("cost")) ;
        String info = (String) params.get("info");
        String type = (String) params.get("type");
        if(type!=null&&info!=null&&cost!=0){
            try {
                Expend expend = new Expend();
                expend.setExpend(cost);
                expend.setExpendType(expendTypeDao.getByName(type));
                expend.setInfo(info);
                expendDao.save(expend);
                jsonObject.put("msg",StaticValue.success);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    @RequestMapping("/getExpendInfo")
    public JSONArray getExpendInfo(){
        JSONArray jsonArray = new JSONArray();
        List list = expendDao.getExpendInfo();
        for (Object aList : list) {
            Object[] obj = (Object[]) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", obj[0]);
            jsonObject.put("value", obj[1]);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private JSONArray getLocations(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            Location location = (Location) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("info", location.getName());
            jsonObject.put("totalCount",pageBean.getAllRow());
            if (location.getAdvertisement() == null)
                jsonObject.put("status", "空");
            else
                jsonObject.put("status", "已有");
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private JSONArray getDeviceTypeList(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            DeviceType deviceType = (DeviceType) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", deviceType.getId());
            jsonObject.put("name", deviceType.getType());
            jsonObject.put("total",pageBean.getAllRow());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private JSONArray getDevice(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            Device device = (Device) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", device.getId());
            jsonObject.put("name", device.getInfo());
            jsonObject.put("location", device.getLocation());
            jsonObject.put("type", device.getDeviceType().getType());
            jsonObject.put("status", device.getStatus());
            jsonObject.put("total",pageBean.getAllRow());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private JSONArray getExpendTypeList(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            ExpendType expendType = (ExpendType) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", expendType.getId());
            jsonObject.put("type", expendType.getType());
            jsonObject.put("total",pageBean.getAllRow());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }


}